"""
调试功率计算脚本 - 检查问题2中的功率计算问题
"""

import numpy as np
from problem2_solver import Problem2Solver

def debug_power_calculation():
    """调试功率计算"""
    print("🔍 调试功率计算问题")
    print("="*60)
    
    # 创建求解器
    solver = Problem2Solver()
    
    # 测试参数（使用更小的尺寸以减少计算量）
    test_params = [0, 0, 4, 4, 3]  # xT, yT, w, h, hm (减小尺寸)
    xT, yT, w, h, hm = test_params
    
    print(f"📋 测试参数:")
    print(f"   吸收塔位置: ({xT}, {yT}) m")
    print(f"   定日镜尺寸: {w} × {h} m")
    print(f"   安装高度: {hm} m")
    print(f"   DNI: {solver.DNI} W/m²")
    
    # 生成定日镜布局
    print("🏗️ 生成定日镜布局...")
    mirror_positions = solver.generate_mirror_layout(w, h, hm, xT, yT)
    print(f"   定日镜数量: {len(mirror_positions)}")
    print(f"   镜面面积: {w * h} m²")
    print(f"   总镜面面积: {len(mirror_positions) * w * h} m²")
    
    # 计算理论最大功率
    total_area = len(mirror_positions) * w * h  # m²
    theoretical_max_power = solver.DNI * total_area / 1e6  # MW
    print(f"   理论最大功率 (100%效率): {theoretical_max_power:.2f} MW")
    
    # 简化功率计算 - 只计算部分时间点
    print("⚡ 计算功率 (简化版本)...")
    
    # 只选择几个代表性时间点
    test_times = [
        (9, 30, 45),    # 上午9点 (太阳高度30°, 方位角45°)
        (12, 60, 0),    # 中午12点 (太阳高度60°, 方位角0°)
        (15, 30, -45),  # 下午3点 (太阳高度30°, 方位角-45°)
    ]
    
    total_power_sum = 0
    valid_times = 0
    
    for hour, elevation_deg, azimuth_deg in test_times:
        print(f"   计算时间点: {hour}:00...")
        
        try:
            # 使用固定的太阳位置
            solar_pos = {
                'elevation': np.radians(elevation_deg), 
                'azimuth': np.radians(azimuth_deg)
            }
            
            if solar_pos['elevation'] > 0:  # 太阳在地平线以上
                # 计算一小部分定日镜的平均功率
                sample_size = min(50, len(mirror_positions))  # 只计算前50个定日镜
                sample_positions = mirror_positions[:sample_size]
                
                power_sum = 0
                for i, pos in enumerate(sample_positions):
                    if i % 10 == 0:  # 每10个显示一次进度
                        print(f"     处理定日镜 {i+1}/{sample_size}...")
                    
                    x, y, z = pos
                    mirror_pos = (x, y)
                    tower_pos = (xT, yT)
                    
                    # 计算效率
                    eta_cos = solver.efficiency_calc._cosine_efficiency(mirror_pos, tower_pos, solar_pos)
                    eta_at = solver.efficiency_calc._atmospheric_efficiency(mirror_pos, tower_pos)
                    
                    # 简化阴影计算 - 使用固定值
                    eta_sb = 0.85  # 假设85%的阴影效率
                    eta_trunc = 0.98
                    eta_ref = 0.88
                    
                    eta_total = eta_cos * eta_at * eta_sb * eta_trunc * eta_ref
                    mirror_power = solver.DNI * (w * h) * eta_total / 1e6  # MW
                    power_sum += mirror_power
                
                # 估算总功率
                avg_power_per_mirror = power_sum / sample_size
                estimated_total_power = avg_power_per_mirror * len(mirror_positions)
                
                total_power_sum += estimated_total_power
                valid_times += 1
                
                print(f"     时间点功率: {estimated_total_power:.2f} MW")
                print(f"     样本平均效率: {(power_sum * 1e6 / (solver.DNI * w * h * sample_size)):.3f}")
            else:
                print("     太阳在地平线以下，跳过")
                
        except Exception as e:
            print(f"     计算出错: {e}")
            import traceback
            traceback.print_exc()
    
    if valid_times > 0:
        avg_power = total_power_sum / valid_times
        avg_efficiency = avg_power / theoretical_max_power if theoretical_max_power > 0 else 0
        
        print(f"\n📊 估算结果:")
        print(f"   平均功率: {avg_power:.2f} MW")
        print(f"   平均效率: {avg_efficiency:.3f}")
        print(f"   定日镜数量: {len(mirror_positions)}")
        
        # 检查是否达到60MW要求
        print(f"\n✅ 约束检查:")
        print(f"   功率要求 (≥60MW): {'✅' if avg_power >= 60 else '❌'} ({avg_power:.2f} MW)")
        
        if avg_power < 60:
            print(f"\n🚨 功率不足分析:")
            print(f"   缺少功率: {60 - avg_power:.2f} MW")
            needed_mirrors = int(60 / (avg_power / len(mirror_positions)))
            print(f"   需要的定日镜数量: {needed_mirrors}")
            print(f"   建议增大定日镜尺寸或优化布局")
        else:
            print(f"\n🎉 功率满足要求!")
    else:
        print("❌ 没有有效的计算结果")

if __name__ == "__main__":
    debug_power_calculation() 